package org.book.configuration.Handler;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.book.common.JsonResult;
import org.book.configuration.aop.NoCheckLogin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
@Slf4j
public class SpringMvcHandler extends HandlerInterceptorAdapter {
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {

    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        HandlerMethod hm = null;
        Method method = null;
        if(handler instanceof HandlerMethod) {
            hm = (HandlerMethod) handler;
            method = hm.getMethod();// 获取方法
        } else {
            return true;
        }
        // 该方法是否添加 允许未登录访问注解
        if (method !=null &&  method.isAnnotationPresent(NoCheckLogin.class)) {
            // 不拦截
            return true;
        }


        String name = (String) request.getSession().getAttribute("user");
        if (name != null) {
            return true;
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {


                out = response.getWriter();
                out.append(new JSONObject().toJSONString(JsonResult.renderFail("用户未登录")) );

            }catch (Exception e){
                out = response.getWriter();
                out.append(new JSONObject().toJSONString(JsonResult.renderError("后台出错")));
                log.info(e.getStackTrace().toString());

            }
            return false;
        }

    }
}

